package cn.orange.ch07_binarytree;

import cn.orange.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * LC105.从中序与后序遍历序列构造二叉树
 */
public class LC106 {
    private Map<Integer, Integer> map;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return build(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

    private TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if (inStart >= inEnd || postStart >= postEnd) return null;
        int rootVal = postorder[postEnd - 1];
        int rootIndex = map.get(rootVal);
        TreeNode root = new TreeNode(rootVal);
        int leftLen = rootIndex - inStart;
        root.left = build(inorder, inStart, rootIndex, postorder, postStart, postStart + leftLen);
        root.right = build(inorder, rootIndex + 1, inEnd, postorder, postStart + leftLen, postEnd - 1);
        return root;
    }

    public static void main(String[] args) {
        LC106 alg = new LC106();
        int[] inorder = new int[]{9, 3, 15, 20, 7};
        int[] postorder = new int[]{9, 15, 7, 20, 3};
        TreeNode treeNode = alg.buildTree(inorder, postorder);
        System.out.println(treeNode);
    }
}
